package com.ruan.controller;

import com.aliyun.oss.common.utils.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruan.common.Code;
import com.ruan.common.Result;
import com.ruan.common.StatusMessageConstant;
import com.ruan.mapper.*;
import com.ruan.pojo.*;
import com.ruan.pojoExt.*;
import com.ruan.service.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping("/project")
public class ProjectController {
    @Autowired
    private ProjectService projectService;
    @Autowired
    private ParticipantService participantService;
    @Autowired
    private ProjectAssignmentsMapper projectAssignmentsMapper;
    @Autowired
    private PositionService positionService;
    @Autowired
    private TasksService tasksService;
    @Autowired
    private ClientService clientService;
    @Autowired
    private ClientMapper clientMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ProjectAssignmentsService projectAssignmentsService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ParticipantMapper participantMapper;
    @Autowired
    private FileService fileService;
    @Autowired
    private FileMapper fileMapper;
    @Value("${kejiu.path}")//必须是org.springframework.beans.factory.annotation提供的Value
    private String basePath;

    //项目信息分页查询
    //创建一个controller方法，接收页面发送的请求并且接收参数（page,pageSize,name）
    @PostMapping("/page/{currentPage}/{pageSize}")
    @Transactional
    @ApiOperation(value = "项目信息分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "页码", required = true, paramType = "path", dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = true, paramType = "path", dataType = "int"),
            @ApiImplicitParam(name = "queryProjectCondition", value = "项目信息查询条件", required = false, paramType = "body",
                    dataType = "QueryProjectCondition")
    })
//    @Cacheable(value = "projectCache",
//            key = "#currentPage + '_' " +
//                    "+ #pageSize + '_' " +
//                    "+ #queryProjectCondition",
//            unless = "#result == null")//加了缓存不能实时更新
    public Result page(@PathVariable int currentPage,
                       @PathVariable int pageSize,
                       @RequestBody QueryProjectCondition queryProjectCondition){//, String cname第三个参数 name 可能是从前端的用户输入或者页面的搜索框中获取的
        //System.out.println("project的page传来的参数是："+currentPage+pageSize+queryProjectCondition);
        Page<Project> iPage=new Page<>(currentPage,pageSize);
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper();
//        System.out.println("getProjectName是null还是''："+queryProjectCondition.getProjectName());
        //搜索框1项目名字输入模糊搜索
        queryWrapper.like(!queryProjectCondition.getProjectName().equals("") &&
                        queryProjectCondition.getProjectName()!=null,
                Project::getProjectName,queryProjectCondition.getProjectName());
        //搜索框2项目编号输入模糊搜索
        queryWrapper.like(!queryProjectCondition.getPid().equals("") &&
                        queryProjectCondition.getPid()!=null,
                Project::getPid,queryProjectCondition.getPid());

        //搜索框3客户名字输入模糊搜索
        LambdaQueryWrapper<Client> queryWrapper1 = new LambdaQueryWrapper();
        queryWrapper1.like(!queryProjectCondition.getClientName().equals("") &&
                        queryProjectCondition.getClientName()!=null,
                Client::getName,queryProjectCondition.getClientName());
        List<Client> clientList = clientMapper.selectList(queryWrapper1);
        List<Long> clientIds = clientList.stream().map(Client::getId).collect(Collectors.toList());
        if (clientIds == null || clientIds.size() == 0) {
            queryWrapper.eq(!queryProjectCondition.getClientName().equals("") &&
                            queryProjectCondition.getClientName()!=null,
                    Project::getClientId, -1);
            // 输入框输入了客户名，不能不查，但是为了防止clientIds为空时查询报错，这里设置一个不存在的id
        } else {
            queryWrapper.in(!queryProjectCondition.getClientName().equals("") &&
                    queryProjectCondition.getClientName()!=null,
                    Project::getClientId, clientIds);
        }
        //负责人名字输入模糊搜索，可能是空
        //LambdaQueryWrapper<Employee> queryWrapper2 = new LambdaQueryWrapper();
//        System.out.println("getEmployeeName是null还是''："+queryProjectCondition.getEmployeeName());
        // TODO 前端注释掉queryCondition的employeeName: ''之后(不根据负责人名查询了)，这里会报空指针，
        //  因为queryProjectCondition.getEmployeeName()是null，要么加if，要么删掉这段

        //项目完成状态下拉框搜索
        //搜索框4根据完成状态查询
        queryWrapper.like(!queryProjectCondition.getCompletionStatus().equals("") &&
                        queryProjectCondition.getCompletionStatus()!=null,
                Project::getCompletionStatus,queryProjectCondition.getCompletionStatus());//!=null,

        //搜索框5根据时间范围搜索
        List<LocalDateTime> dateRange = queryProjectCondition.getDateRange();
        //System.out.println("dateRange是:"+dateRange);
        if (dateRange != null && dateRange.size() == 2) {
            LocalDate startDate = LocalDate.from(dateRange.get(0).plusDays(1).toLocalDate().atStartOfDay()); // 由于时区的影响，需要加一天
//            System.out.println("开始时间："+startDate);
            LocalDate endDate = LocalDate.from(dateRange.get(1).plusDays(1).toLocalDate().atStartOfDay());
//            System.out.println("结束时间："+endDate);
            // 进行日期转换和查询
            queryWrapper.between(Project::getCreateTime, startDate, endDate);
        }

        //搜索框6根据项目负责人搜索
        LambdaQueryWrapper<Employee> queryWrapper2 = new LambdaQueryWrapper();
        queryWrapper2.like(!queryProjectCondition.getEmployeeName().equals("") &&
                        queryProjectCondition.getEmployeeName()!=null,
                Employee::getName,queryProjectCondition.getEmployeeName());
        List<Employee> employeeList1 = employeeMapper.selectList(queryWrapper2);
        List<Long> employeeIds = employeeList1.stream().map(Employee::getId).collect(Collectors.toList());
//        System.out.println("employeeIds是:"+employeeIds);
        if (employeeIds == null || employeeIds.size() == 0) {
            queryWrapper.eq(!queryProjectCondition.getEmployeeName().equals("") &&
                    queryProjectCondition.getEmployeeName()!=null,
                    Project::getEmployeeId, -1);
            // 输入框输入了客户名，不能不查，但是为了防止clientIds为空时查询报错，这里设置一个不存在的id
        } else {
            //查询结果将包括 employeeId 在给定列表中的记录，以及所有 employeeId 为空的记录。
//            queryWrapper.in(Project::getEmployeeId, employeeIds).or().isNull(Project::getEmployeeId);
            queryWrapper.in(!queryProjectCondition.getEmployeeName().equals("") &&
                    queryProjectCondition.getEmployeeName()!=null,
                    Project::getEmployeeId, employeeIds);
        }

        String employeeId1 = queryProjectCondition.getEmployeeId();
//说明是个人查询自己的项目
        if(employeeId1 != null){
//            System.out.println("个人查询自己的项目"+employeeId1);
//根据负责人id查询，只要是参与人员都可以看到自己参与的项目
        LambdaQueryWrapper<Participant> participantQueryWrapper = new LambdaQueryWrapper<>();
        participantQueryWrapper.eq(!employeeId1.equals("") && employeeId1!=null,
                Participant::getEmployeeId,employeeId1);//employeeId是当前登陆人的员工id
        List<Participant> participantList1 = participantMapper.selectList(participantQueryWrapper);
//            System.out.println("participantList1是"+participantList1);
            List<Long> projectIds = new ArrayList<>();
        if(participantList1.size() > 0){
            projectIds = participantList1.stream().map(Participant::getProjectId).collect(Collectors.toList());
        }
//        System.out.println("projectIds是"+projectIds);
        if(projectIds == null || projectIds.size() == 0){
            queryWrapper.in(Project::getId, -1);
        } else {
            //查全部的时候不能进入到这里
            queryWrapper.in(!employeeId1.equals("") && employeeId1!=null,
                    Project::getId, projectIds);
        }
    }

        Page<ProjectExt> iPageExt = new Page<>();
        queryWrapper.orderByDesc(Project::getEndDate);
        projectService.page(iPage,queryWrapper);//page方法已经已经继承了IService,已经提供了分页查询方法，只需要把Page对象和queryWrapper对象构造好，传给他，自己就会进行分页查询

        BeanUtils.copyProperties(iPage,iPageExt,"records");//从pageInfo一个一个拷贝属性到projectExtPage上(除了records)
        //处理
        List<Project> records = iPage.getRecords();
        //item:遍历出来的每一个项目对象
        List<ProjectExt> list = records.stream().map((item) -> {
            ProjectExt projectExt = new ProjectExt();//只有ProjectExt符合项目管理页面的要求，所以new一个出来,进行填充
            BeanUtils.copyProperties(item,projectExt);//先填充入project的普通属性
            Long clientId = item.getClientId();//拿到了每个项目所对应的项目客户id
            Long employeeId = item.getEmployeeId();//拿到了每个项目所对应的负责人id


             LambdaQueryWrapper<Participant> queryWrapper3 = new LambdaQueryWrapper<>();
             queryWrapper3.eq(Participant::getProjectId,item.getId());
             List<Participant> participantList = participantMapper.selectList(queryWrapper3);

//            ProjectAssignments projectAssignment = projectAssignmentsMapper.selectById(item.getId());
//              Integer employeeNum = participantMapper.selectCount(queryWrapper3);

                //就可以数一数项目的参与人数
                int employeeNum = participantList.size();
                if(employeeNum > 0){
                    projectExt.setEmployeeNum(employeeNum);
//                    if(!projectAssignment.getParticipants().equals(employeeNum)){
//                        projectExt.setEmployeeNum(employeeNum);
//                        projectAssignment.setParticipants(employeeNum);
//                        projectAssignmentsMapper.updateById(projectAssignment);
//                    }
                    //必须有项目经理，把项目经理也加入到partic表，不需要，因为选择项目经理之后，
                    // 项目经理同时也会添加到参与人员中
                }
//                System.out.println("项目参与人员数："+employeeNum);
                List<Employee> employeeList = new ArrayList<>();
                for(Participant participant : participantList){
                    //根据参与人员查询出参与员工信息
                    Employee employee = employeeService.getById(participant.getEmployeeId());
                    employeeList.add(employee);
                }
                projectExt.setEmployeeList(employeeList);
               Employee employee = new Employee();
                if(employeeId != null) {//负责人可以为空，项目经理都有了，说明组员也有了X
                    // (如果负责人离职了的话，不应该删除其它参与人员，应该是重新选一个负责人)
                    employee = employeeService.getById(employeeId);
                    if(employee != null){//能查到项目的负责人
                        projectExt.setEmployeeName(employee.getName());//填充入projects没有的clientName属性
                        projectExt.setJobId(employee.getJobId());
                    }
                }


            Client client = new Client();
            if(clientId != null) {
                client = clientService.getById(clientId);
                if(client != null){//能查到项目的客户
                    projectExt.setClientName(client.getName());//填充入projects没有的clientName属性
                }
            }

            return projectExt;//填充完新键的projectExt之后，返回，把遍历的这些projectExt对象搜集起来后
        }).collect(Collectors.toList());
        //System.out.println("page/list里有了什么"+list);//.toString()
        iPageExt.setRecords(list);//list获得了改造过后的projectExt集合之后，被用来设置page对象的Records属性
        return new Result(Code.SELECT_OK,iPageExt);
    }

    //分页获取个人负责的项目
//    @PostMapping("/selfPage/{currentPage}/{pageSize}")//@RequestParam("employeeId") String employeeId,
//    public Result selfPage(@PathVariable int currentPage,
//                       @PathVariable int pageSize,
//                       @RequestBody QueryProjectCondition queryProjectCondition){
//        //System.out.println("queryProjectCondition参数是："+employeeId+queryProjectCondition);
//        Page<Project> iPage=new Page<>(currentPage,pageSize);
//        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
//        // 搜索框1根据项目名模糊查询
//        queryWrapper.like(!queryProjectCondition.getProjectName().equals("") &&
//                        queryProjectCondition.getProjectName()!=null,
//                Project::getProjectName,queryProjectCondition.getProjectName());
//        // 搜索框2根据项目编号模糊查询
//        queryWrapper.like(!queryProjectCondition.getPid().equals("") &&
//                        queryProjectCondition.getPid()!=null,
//                Project::getPid,queryProjectCondition.getPid());
//        //搜索框3根据输入客户名字模糊搜索
//        LambdaQueryWrapper<Client> clientQueryWrapper = new LambdaQueryWrapper();
//        clientQueryWrapper.like(!queryProjectCondition.getClientName().equals("") &&
//                        queryProjectCondition.getClientName()!=null,
//                Client::getName,queryProjectCondition.getClientName());
//        List<Client> clientList = clientMapper.selectList(clientQueryWrapper);
//        List<Long> clientIds = clientList.stream().map(Client::getId).collect(Collectors.toList());
//        if (clientIds == null || clientIds.size() == 0) {
//            queryWrapper.eq(Project::getClientId, -1);
//            // 输入框输入了客户名，不能不查，但是为了防止clientIds为空时查询报错，这里设置一个不存在的id
//        } else {
//            queryWrapper.in(Project::getClientId, clientIds);
//        }
//        //搜索框4根据完成状态查询
//        queryWrapper.eq(!queryProjectCondition.getCompletionStatus().equals("") &&
//                        queryProjectCondition.getCompletionStatus()!=null,
//                Project::getCompletionStatus,queryProjectCondition.getCompletionStatus());
//
//        //搜索框5根据时间范围搜索
//        List<LocalDateTime> dateRange = queryProjectCondition.getDateRange();
//        System.out.println("dateRange是:"+dateRange);
//        if (dateRange != null && dateRange.size() == 2) {
//            LocalDate startDate = LocalDate.from(dateRange.get(0).plusDays(1).toLocalDate().atStartOfDay()); // 由于时区的影响，需要加一天
//            System.out.println("开始时间："+startDate);
//            LocalDate endDate = LocalDate.from(dateRange.get(1).plusDays(1).toLocalDate().atStartOfDay());
//            System.out.println("结束时间："+endDate);
//            // 进行日期转换和查询
//            queryWrapper.between(Project::getCreateTime, startDate, endDate);
//        }
//
//        //queryWrapper.eq(Project::getEmployeeId,employeeId);
////根据负责人id查询，只要是参与人员都可以看到自己参与的项目
//        LambdaQueryWrapper<Participant> participantQueryWrapper = new LambdaQueryWrapper<>();
//        String employeeId = queryProjectCondition.getEmployeeId();
//        System.out.println("当前什么参与人查项目："+employeeId);
//        participantQueryWrapper.eq(!employeeId.equals("") && employeeId!=null,
//                Participant::getEmployeeId,employeeId);//employeeId是当前登陆人的员工id
//        List<Participant> participantList1 = participantMapper.selectList(participantQueryWrapper);
//        List<Long> projectIds = new ArrayList<>();
//        if(participantList1 != null){
//            projectIds = participantList1.stream().map(Participant::getProjectId).collect(Collectors.toList());
//        }
//        System.out.println("都参与了什么项目"+projectIds);
//        if(projectIds == null || projectIds.size() == 0){
//            queryWrapper.in(Project::getId, -1);
//        } else {
//            queryWrapper.in(Project::getId, projectIds);
//        }
//
//        Page<ProjectExt> iPageExt = new Page<>();
//        queryWrapper.orderByDesc(Project::getCreateTime);
//        projectService.page(iPage,queryWrapper);//page方法已经已经继承了IService,已经提供了分页查询方法，只需要把Page对象和queryWrapper对象构造好，传给他，自己就会进行分页查询
//
//        BeanUtils.copyProperties(iPage,iPageExt,"records");//从pageInfo一个一个拷贝属性到projectExtPage上(除了records)
//        //处理
//        List<Project> records = iPage.getRecords();
//
//        List<ProjectExt> list = records.stream().map((item) -> {
//            ProjectExt projectExt = new ProjectExt();//只有ProjectExt符合项目管理页面的要求，所以new一个出来,进行填充
//            BeanUtils.copyProperties(item,projectExt);//先填充入project的普通属性
//            Long clientId = item.getClientId();//拿到了每个项目所对应的项目客户id
//            Long employerId = item.getEmployeeId();//拿到了每个项目所对应的负责人id
//
//
//            LambdaQueryWrapper<Participant> queryWrapper3 = new LambdaQueryWrapper<>();
//            queryWrapper3.eq(Participant::getProjectId,item.getId());
//            List<Participant> participantList = participantMapper.selectList(queryWrapper3);
////              Integer employeeNum = participantMapper.selectCount(queryWrapper3);
//
//            //就可以数一数项目的参与人数
//            int employeeNum = participantList.size();
//            if(participantList.size() > 0){
//                projectExt.setEmployeeNum(employeeNum);
//                //必须有项目经理，把项目经理也加入到partic表，不需要，因为选择项目经理之后，
//                // 项目经理同时也会添加到参与人员中
//            }
////                System.out.println("项目参与人员数："+employeeNum);
//            List<Employee> employeeList = new ArrayList<>();
//            for(Participant participant : participantList){
//                //根据参与人员查询出参与员工信息
//                Employee employee = employeeService.getById(participant.getEmployeeId());
//                employeeList.add(employee);
//            }
//            projectExt.setEmployeeList(employeeList);
//            Employee employee = new Employee();
//            if(employerId != null) {//负责人可以为空，项目经理都有了，说明组员也有了X
//                // (如果负责人离职了的话，不应该删除其它参与人员，应该是重新选一个负责人)
//                employee = employeeService.getById(employerId);
//            }
//
//            if(employee != null){//能查到项目的负责人
//                projectExt.setEmployeeName(employee.getName());//填充入projects没有的clientName属性
//            }
//
//            //根据clientId查客户(表)(需要注入clientService)，把clientName拿到
//            Client client = clientService.getById(clientId);
//
//            if(client != null){//能查到项目的客户
//                projectExt.setClientName(client.getName());//填充入projects没有的clientName属性
//            }
//            return projectExt;//填充完新键的projectExt之后，返回，把遍历的这些projectExt对象搜集起来后
//        }).collect(Collectors.toList());
//        //System.out.println("page/list里有了什么"+list);//.toString()
//        iPageExt.setRecords(list);//list获得了改造过后的projectExt集合之后，被用来设置page对象的Records属性
//        return new Result(Code.SELECT_OK,iPageExt);
//    }

    /**
     * 导出所有项目表
     */
    @GetMapping("/exportToExcel")
    public ResponseEntity<byte[]> exportToExcel(){
        try {
            Integer id = null;
            byte[] excelBytes = projectService.exportToExcel(id);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
            headers.setContentDispositionFormData("attachment", "项目表.xlsx");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(excelBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    /**
     * 导出单个人的项目表
     */
    @GetMapping("/exportToExcel/{id}")
    public ResponseEntity<byte[]> exportToExcel(@PathVariable Integer id) {
        try {
            byte[] excelBytes = projectService.exportToExcel(id);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
            headers.setContentDispositionFormData("attachment", "项目表.xlsx");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(excelBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    @GetMapping("/deleteProject/{id}")
    public Result deleteProject(@PathVariable Integer id){
        if(projectService.getById(id) == null){
            return new Result(Code.DELETE_ERR,"项目信息不存在，删除失败！");
        }
        //有任务未完成不能删除
        if(getTodayTasks(id)){
            return new Result(Code.DELETE_ERR,"今天有相关任务未完成，不能删除！");
        }
        //System.out.println("deleteProject传来的id是"+id);
        if (projectService.deleteProject(id)){
            return new Result(Code.DELETE_OK,"项目删除成功！");
        }

        return new Result(Code.DELETE_ERR,"项目删除失败！");
    }

    private boolean getTodayTasks(Integer id){
        LambdaQueryWrapper<Tasks> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Tasks::getProjectId,id);
        queryWrapper.eq(Tasks::getDate,LocalDate.now());
        queryWrapper.eq(Tasks::getCompletionStatus,Tasks.CompletionStatus.incomplete);
        if(tasksService.list(queryWrapper).size() > 0){
            return true;
        }
        return false;
    }

    @GetMapping("/checkProjectExists/{id}")
    public Result checkProjectExists(@PathVariable Integer id){
        if(projectService.getById(id) == null){
            return new Result(Code.SELECT_ERR,"该项目信息不存在！");
        }
        return new Result(Code.SELECT_OK,"项目信息存在！");
    }

   //检查有没有待分配的项目
    @GetMapping("/checkPendingTasks")
    public Result checkTodayTasks(@RequestParam String employeeId) {
        List<ProjectExt> projectExtList = projectService.getTodayProjects(employeeId);
        if(projectExtList.size() == 0){
            return new Result(Code.SELECT_ERR,"今日项目查找失败");
        }
        return new Result(Code.SELECT_OK,projectExtList,"今日项目查找成功");
    }

    @GetMapping("/checkExistence/{id}")//不能删除正在合作的客户
    @Transactional
    public Result checkExistence(@PathVariable Integer id){
//        System.out.println("checkExistence传来的(客户)id是"+id);
        if(clientService.getById(id) == null){
            return new Result(Code.SELECT_ERR,"客户信息不存在，删除失败！");
        }
       LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Project::getClientId,id);
        queryWrapper.ne(Project::getCompletionStatus, Project.CompletionStatus.completed);
        List<Project> projectList = projectMapper.selectList(queryWrapper);
        if (projectList.size() > 0){
            //纠正合作状态
            Client client = clientService.getById(id);
            if(client != null) {
                client.setStatus(1);
                clientService.updateById(client);
            }
            return new Result(Code.SELECT_OK,"该客户合作中！");
        }
        //纠正合作状态
        Client client = clientService.getById(id);
        if(client != null){
            client.setStatus(0);
            clientService.updateById(client);
        }
        return new Result(Code.SELECT_ERR,"该客户未合作！");
    }

    /**
     * 根据项目id查询单个项目资源利用的详细记录
     * @param projectId 查询条件：项目id
     * @return
     */
    @PostMapping("/getProjectDetailInfo")
    public Result getProjectDetailInfo(@RequestParam("projectId") String projectId,
                                       @RequestBody QueryFilesCondition queryFilesCondition){
//        System.out.println("传过来的项目参数是："+queryFilesCondition);
        Project project = projectService.getById(projectId);
        LambdaQueryWrapper<Participant> participantWrapper = new LambdaQueryWrapper<>();
//        LambdaQueryWrapper<ProjectToolAssignment> projectToolAssignmentWrapper = new LambdaQueryWrapper<>();
        participantWrapper.eq(Participant::getProjectId,projectId);
//        projectToolAssignmentWrapper.eq(ProjectToolAssignment::getProjectId,projectId);

        List<Participant> participantList = participantMapper.selectList(participantWrapper);
//        List<ProjectToolAssignment> projectToolAssignmentList = projectToolAssignmentMapper.selectList(projectToolAssignmentWrapper);


        ProjectResourceExt projectResourceExt = new ProjectResourceExt();
        if(project!=null){
            BeanUtils.copyProperties(project,projectResourceExt);
        }
        //根据项目id查询到了这个项目用到什么人
        List<EmployeeExt> employeesExt = new ArrayList<>();
        for(Participant participant : participantList){
           Employee employee = employeeService.getById(participant.getEmployeeId());
            EmployeeExt employeeExt = new EmployeeExt();
            BeanUtils.copyProperties(employee,employeeExt);

            Position position = positionService.getById(employee.getPositionId());
            if(position!=null){
                employeeExt.setPosition(position.getPname());
            }
            employeesExt.add(employeeExt);
        }
        projectResourceExt.setEmployeesExt(employeesExt);
//        projectResourceExt.setTotalOriginalPay(totalOriginalPay);

        //根据项目id查询到了这个项目用到什么文件
        LambdaQueryWrapper<FileEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FileEntity::getProjectId, projectId);
        //查找软删除的
        queryWrapper.eq(FileEntity::getIsDelete, FileEntity.IsDelete.exist);

        //搜索框1根据文件名模糊查询
        queryWrapper.like(!queryFilesCondition.getFileName().equals("") &&
                        queryFilesCondition.getFileName()!=null,
                FileEntity::getFileName,queryFilesCondition.getFileName());

        //搜索框2根据上传人称模糊查询
        LambdaQueryWrapper<Employee> queryWrapper2 = new LambdaQueryWrapper();
        queryWrapper2.like(!queryFilesCondition.getEmployeeName().equals("") &&
                        queryFilesCondition.getEmployeeName()!=null,
                Employee::getName,queryFilesCondition.getEmployeeName());
        List<Employee> employeeList1 = employeeMapper.selectList(queryWrapper2);
        List<Long> employeeIds = employeeList1.stream().map(Employee::getId).collect(Collectors.toList());
//        System.out.println("employeeIds是:"+employeeIds);
        if (employeeIds == null || employeeIds.size() == 0) {
            queryWrapper.eq(FileEntity::getEmployeeId, -1);
            // 输入框输入了客户名，不能不查，但是为了防止clientIds为空时查询报错，这里设置一个不存在的id
        } else {
            //查询结果将包括 employeeId 在给定列表中的记录，以及所有 employeeId 为空的记录。
//            queryWrapper.in(Project::getEmployeeId, employeeIds).or().isNull(Project::getEmployeeId);
            queryWrapper.in(!queryFilesCondition.getEmployeeName().equals("") &&
                            queryFilesCondition.getEmployeeName()!=null,
                    FileEntity::getEmployeeId, employeeIds);
        }

        List<FileEntity> fileEntities = fileMapper.selectList(queryWrapper);
        List<FileEntityExt> fileEntitiesExt = new ArrayList<>();

//        fileEntities.forEach//以访问路径作为文件名
//                (fileEntity -> fileEntity.setFileName(basePath+fileEntity.getFileName()));
        //普通属性 BeanUtils.copyProperties只能从一个对象复制到另外一个对象，不能是列表之间
        for (FileEntity fileEntity : fileEntities) {
                FileEntityExt fileEntityExt = new FileEntityExt();
                BeanUtils.copyProperties(fileEntity, fileEntityExt);
                //特殊属性：设置上传人姓名
                Employee employee = employeeService.getById(fileEntity.getEmployeeId());
                if(employee!=null) {
                    fileEntityExt.setEmployeeName(employee.getName());
                }
                // 设置文件路径
                if(fileEntity!=null){
                    fileEntityExt.setFileName(basePath + fileEntity.getFileName());
                }
                // 添加到列表
                fileEntitiesExt.add(fileEntityExt);
        }

        //设置文件列表
        projectResourceExt.setFileEntitiesExt(fileEntitiesExt);
        //System.out.println("该项目有关的所有文件是："+fileEntitiesExt);


        //项目负责人
        Employee employee = new Employee();
        if (project != null) {
            Long employeeId = project.getEmployeeId();
            if (employeeId != null) {
                employee = employeeService.getById(employeeId);
            }
        }

        if(employee!=null){
            projectResourceExt.setEmployerName(employee.getName());
        }


        //相关客户名
        Client client = new Client();
        if (project != null) {
            Long clientId = project.getClientId();
            if (clientId != null) {
                client = clientService.getById(clientId);
            }
        }

        if(client!=null) {
            projectResourceExt.setClientName(client.getName());
        }
        if (projectResourceExt!=null){
            return new Result(Code.SELECT_OK,projectResourceExt);
        }
        return new Result(Code.SELECT_ERR,projectResourceExt);
    }

    //项目名独一无二验证
    @GetMapping("/checkUniqueProjectName")
    public boolean checkUniqueProjectName(@RequestParam String projectName) {
//        System.out.println("checkUniqueProjectName能生效吗"+projectName);
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Project::getProjectName, projectName);
        return projectMapper.selectCount(queryWrapper) == 0;
    }

    //项目编号独一无二验证
    @GetMapping("/checkUniquePid")
    public boolean checkUniquePid(@RequestParam String pid) {
//        System.out.println("checkUniqueProjectName能生效吗"+projectName);
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Project::getPid, pid);
        return projectMapper.selectCount(queryWrapper) == 0;
    }

    /**
     * 项目进度更新
     */
    @GetMapping("/updateProjectStatus/{id}")
    //@GlobalTransactional是 Seata (或其他分布式事务框架) 提供的注解，用于管理分布式事务。
    // 它能够协调多个数据库或服务的多个事务，保证数据的一致性。
    // Seata 使用两阶段提交或TCC模式等机制来实现分布式事务。
    // @GlobalTransactional 通常作用于方法级别
//    @GlobalTransactional
    //@Transactional是 Spring Framework 提供的标准事务注解，
    // 用于管理单个数据库或数据源的事务,通常作用于方法或类级别。
    @Transactional//(rollbackFor = Exception.class)//添加 rollbackFor = Exception.class 来显式地声明所有异常都应该导致事务回滚，包括检查异常
    //rollbackFor 属性指定了哪些类型的异常会导致事务回滚。
    // 默认情况下，@Transactional 只会在发生运行时异常
    // (RuntimeException 及其子类) 时回滚事务，
    // 而检查异常 (Exception 及其子类，但不包括 RuntimeException)
    // 则不会导致事务回滚。
    public Result updateProjectStatus(@PathVariable Integer id){
//        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper();
//        queryWrapper.eq(Project::getId,id);
//        Project project = projectMapper.selectOne(queryWrapper);
        Project project = projectMapper.selectById(id);
        if(project!=null){
            if(project.getCompletionStatus() == Project.CompletionStatus.inPreparation){
                project.setCompletionStatus(Project.CompletionStatus.onGoing);
            }else if(project.getCompletionStatus() == Project.CompletionStatus.onGoing){
                project.setCompletionStatus(Project.CompletionStatus.deBugging);
            }else if(project.getCompletionStatus() == Project.CompletionStatus.deBugging){
                project.setCompletionStatus(Project.CompletionStatus.waitForCheck);
            }else if(project.getCompletionStatus() == Project.CompletionStatus.waitForCheck){
                project.setCompletionStatus(Project.CompletionStatus.completed);
                project.setCompletionTime(LocalDateTime.now());
                //修改客户状态为未合作
                LambdaQueryWrapper<Project> queryWrapper1 = new LambdaQueryWrapper();
                queryWrapper1.eq(Project::getClientId,project.getClientId());
                queryWrapper1.ne(Project::getCompletionStatus,Project.CompletionStatus.completed);
                queryWrapper1.ne(Project::getId,id);
                int count = projectMapper.selectCount(queryWrapper1);
//                System.out.println("count是"+count);
                if(count==0){//该客户没有其它项目合作，则修改该客户状态为未合作
                    Client client = clientService.getById(project.getClientId());
                    if(client!=null){
                        client.setStatus(0);
                        clientService.updateById(client);
                    }
                }
            }else{
                return new Result(Code.UPDATE_ERR,"项目已经完成，不能再更新进度！");
            }
            projectMapper.updateById(project);
            //更新到数据库
            return new Result(Code.UPDATE_OK,"项目进度更新成功！");
        }
        return new Result(Code.UPDATE_ERR,"项目不存在，进度更新失败！");
    }

    /**
     * 查询所有未分配负责人和员工的项目名字以及id
     * @return
     */
    @GetMapping("/getPnameAndId")
    public Result getAllProjectsNameAndId(){//R<List<Project>>
        //System.out.println("查询所有未分配负责人和员工的项目名字以及id");

        //前端选择负责人时，同时也会给下面的参与员工插入自己的信息作为参与人员，
        // 但是有可能有人把它故意取消，所以不能用participant去查，
        // 因为可能一个项目已经分配了负责人了，但是负责人未作为参与员工插入到participant项目参与表里，
//        List<Long> projectIdsInParticipant = participantMapper.selectList(
//                        new LambdaQueryWrapper<Participant>().select(Participant::getProjectId))
//                .stream()
//                .map(Participant::getProjectId)
//                .collect(Collectors.toList());
//
//        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
//        if (projectIdsInParticipant.size() > 0) {
//            queryWrapper.notIn(Project::getId, projectIdsInParticipant);
//        }
//        List<Project> projectList = projectMapper.selectList(queryWrapper);

        //System.out.println("getPnameAndId项目有"+projectList);
//        if(projectList!=null){
//            //查出来才返回@PathVariable Long id
//            return new Result(Code.SELECT_OK,projectList,"查询项目成功");
//        }
//        return new Result(Code.SELECT_ERR,"项目名字为空");

        //应该查该项目的负责人，查到就说明这个项目已经分配了
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        // 查找 employeeId(负责人Id)为空的记录
        queryWrapper.isNull(Project::getEmployeeId);
        // 执行查询
        List<Project> projectsWithNullEmployeeId = projectMapper.selectList(queryWrapper);
        // 处理查询结果
        if (projectsWithNullEmployeeId.size() > 0) {
            // 可以输出这些记录或进行其他处理
//            projectsWithNullEmployeeId.forEach(project -> {
//                System.out.println("项目ID: " + project.getId() + "，项目名称: " + project.getName());
//            });
           // System.out.println("查询到了没有负责人的项目成功");
            return new Result(Code.SELECT_OK,projectsWithNullEmployeeId,"查询到了没有负责人的项目");
        }
            //System.out.println("没有找到 employeeId 为空的记录。");
        return new Result(Code.SELECT_ERR,"没有找到项目负责人为空的记录");

    }

    //弃用。。。。//需要分页
    @GetMapping("/getProjectIdAndName")
    public Result getProjectIdAndName(@RequestParam("id") String id){
//        System.out.println("当前登录用户的id是"+id);
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Project::getEmployeeId,id)//queryWrapper.ge  表示"大于等于"
                .ge(Project::getEndDate,new Date());// 截止时间晚于当前时间的记录(项目未结束)
        int count = projectMapper.selectCount(queryWrapper);
        if (count > 0) {
            List<Project> projectList = projectMapper.selectList(queryWrapper);
            return new Result(Code.SELECT_OK,projectList,"负责的项目查询成功");
        } else {
            return new Result(Code.SELECT_ERR,"该员工手上没有项目");
        }
    }

    //被分配到项目的员工，登录时，可以给该项目的员工分配任务
    @GetMapping("/getAllproject")
    public Result getAllProjects(){
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.le(Project::getEndDate, new Date()); // 筛选出截止时间早于当前时间的记录
        //queryWrapper.gt  表示"大于"（greater than）
        // 截止时间晚于当前时间的记录(项目未结束)
        queryWrapper.gt(Project::getEndDate, new Date());
        int count = projectMapper.selectCount(queryWrapper);
        //System.out.println("截止时间晚于当前时间的记录："+projectList);
        if(count > 0){
            List<Project> projectList = projectMapper.selectList(queryWrapper);
            return new Result(Code.SELECT_OK,projectList,"项目列表查询成功");
        }
        return new Result(Code.SELECT_ERR,"项目列表查询失败");
    }


    @PutMapping("/updateProject")
    @Transactional
    public Result update(@RequestBody Map<String, Object> params){//@RequestBody Project project
//‘@RequestBody’注释表明‘Projects’对象将从请求体中反序列化，通常采用JSON或XML格式。
        System.out.println("修改项目信息："+params);
        //项目负责人没填，不允许修改
        if(params.get("employeeId")==null){
            return new Result(Code.UPDATE_ERR,"请选择项目负责人");
        }

        Project project = new Project();

        if(params.get("endDate")!=null){
            //params.get("endDate") 返回的是 "2024-05-06 17:22:00"
            String endDateStr = params.get("endDate").toString();
            // 定义一个 DateTimeFormatter，指定输入的日期时间格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // 使用 formatter 解析字符串
            LocalDateTime endDate = LocalDateTime.parse(endDateStr, formatter);
            // 将解析后的 LocalDateTime 设置到 project 对象
//            System.out.println("项目名截止日期是："+endDate);
            project.setEndDate(endDate);
        }

        project.setId(Long.valueOf(params.get("id").toString()));
        if(params.get("pid")!=null){
            project.setPid(params.get("pid").toString());
        }
        if(params.get("projectName")!=null){
            project.setProjectName(params.get("projectName").toString());
        }
        if(params.get("employeeId")!=null && !params.get("employeeId").toString().equals("")){
            Employee employee = employeeMapper.selectById(Long.valueOf(params.get("employeeId").toString()));
            if (employee == null || employee.getStatus().equals("离职")) {
                projectService.update(new UpdateWrapper<Project>().lambda()
                        .set(Project::getEmployeeId,null)
                        .eq(Project::getId,project.getId()));
                LambdaQueryWrapper<ProjectAssignments> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(ProjectAssignments::getEmployeeId,employee.getId());
                queryWrapper.eq(ProjectAssignments::getProjectId,project.getId());
                projectAssignmentsService.remove(queryWrapper);
                LambdaQueryWrapper<Participant> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(Participant::getEmployeeId,employee.getId());
                queryWrapper1.eq(Participant::getProjectId,project.getId());
                participantService.remove(queryWrapper1);
                return new Result(Code.UPDATE_ERR,"该负责人已离职，请重新选择");
            }

            if(!employee.getStatus().equals("离职")){
                project.setEmployeeId(Long.valueOf(params.get("employeeId").toString()));
            }
        }

        //TODO 报错
        if (params.get("actualAmount") != null) {
            String actualAmountStr = params.get("actualAmount").toString();
//            System.out.println("总金额是"+actualAmountStr);
            //BigDecimal actualAmount = null;
            // 检查字符串是否非空且是有效的数字
            if (actualAmountStr.trim().isEmpty() || actualAmountStr.isBlank()) {
                //传的是空，给个0值
                actualAmountStr = String.valueOf(0);
                BigDecimal actualAmount = new BigDecimal(actualAmountStr);
                project.setActualAmount(actualAmount);
            }else{
                BigDecimal actualAmount = new BigDecimal(actualAmountStr);
                project.setActualAmount(actualAmount);
            }
        }
        if(params.get("currency")!=null){
            project.setCurrency(Project.Currency.valueOf(params.get("currency").toString()));
        }
        if(params.get("description")!=null){
            project.setDescription(params.get("description").toString());
        }
//        System.out.println("params.get(clientId)是"+params.get("clientId"));
        if(params.get("clientId")!=null && !params.get("clientId").toString().isEmpty()){
            project.setClientId(Long.valueOf(params.get("clientId").toString()));
            //更新客户的合作状态
//            System.out.println("更新客户的合作状态"+project.getClientId());
            Client client = clientService.getById(project.getClientId());
            if(client!=null){
                client.setStatus(1);
                clientMapper.updateById(client);
            }

        }
//        System.out.println("封装后的项目对象："+ project);
        //TODO 先删除所有的Participant参与人员，再重新插入
        //并不会将 List<String> 中的每个元素实际转换为 Long 类型。它仅仅是将从 params.get("employeeIds") 返回的列表视为 List<Long>，
        // 实际上列表中的元素仍然是 String 类型。这将导致在你尝试以 Long 类型使用这些元素时抛出 ClassCastException
        List<String> rawEmployeeIds = (List<String>) params.get("employeeIds"); // 假设它是 String 类型
        List<Long> employeeIds = rawEmployeeIds.stream()
                // 将每个 String 都转换为 Long
                .map(Long::valueOf)
                // 重新收集成 List<Long>
                .collect(Collectors.toList());
//        System.out.println("employeeIds是"+employeeIds);
        participantMapper.delete(new LambdaQueryWrapper<Participant>()
                .eq(Participant::getProjectId,project.getId()));

        //当 employeeIds 为空时，for (Long employeeId : employeeIds) 这个循环将不会执行
        for (Long employeeId : employeeIds) {
            Employee employee = employeeService.getById(employeeId);
            if (employee.getStatus().equals("离职")) {
                // 如果 employee 离职了，则跳过当前循环
//                System.out.println("跳过离职员工：" + employeeId);
//                continue;
                // 如果有一个 employee 离职了，则需要重新选择
//                System.out.println("需要重新选择：" + employeeId);

//                LambdaQueryWrapper<Participant> queryWrapper = new LambdaQueryWrapper<>();
//                queryWrapper.eq(Participant::getEmployeeId,employeeId);
//                queryWrapper.eq(Participant::getProjectId,project.getId());
//                participantService.remove(queryWrapper);
                //想要回滚就要报个异常
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return new Result(Code.UPDATE_ERR, "员工" + employee.getName() + "已离职，请重新选择");
            }
            Participant participant = new Participant();
            participant.setProjectId(project.getId());
            participant.setEmployeeId(Long.valueOf(employeeId));
            //插入之前先查查数据库，该项目可能被另一个用户删除了
            Project project1 = projectMapper.selectById(project.getId());
            if(project1==null){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return new Result(Code.UPDATE_ERR,"项目已被删除，无法修改");
            }
            participantMapper.insert(participant);
        }
        //根据项目id更新/新增项目分配表(中的负责人id和参与人数)
        LambdaQueryWrapper<ProjectAssignments> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectAssignments::getProjectId,project.getId());
        ProjectAssignments projectAssignment = new ProjectAssignments();
// 查询符合条件的所有记录
        List<ProjectAssignments> recordList = projectAssignmentsMapper.selectList(queryWrapper);

// 如果记录数大于 1 条,则需要随机删除多余的记录
        if (recordList.size() > 1) {
            // 从第二条记录开始截取多余的记录
            List<ProjectAssignments> extraRecords = recordList.subList(1, recordList.size());
            // 随机删除多余的记录
            for (ProjectAssignments record : extraRecords) {
                projectAssignmentsMapper.deleteById(record.getId());
            }
        }else{
            projectAssignment = projectAssignmentsMapper.selectOne(queryWrapper);
        }

        ProjectAssignments projectAssignment1 = new ProjectAssignments();
//        System.out.println("projectAssignment有值吗"+projectAssignment);
        //项目负责人不为空时(负责人都没填，就没必要更新或新建分配表)，且项目分配表不为空时，才能更新项目分配信息(就是为了更新参与数)
        if(project.getEmployeeId()!=null && projectAssignment!=null){
//            System.out.println("更新项目分配信息");
            projectAssignment.setEmployeeId(project.getEmployeeId());
        //项目负责人不为空时，且项目分配表为空时，才能新增项目分配信息(就是为了更新参与数)
        }else if(project.getEmployeeId()!=null && projectAssignment ==null){
            //查不到该项目分配信息，则插入
//            System.out.println("新增项目分配信息"+project.getId()+projectAssignment1);
            if(project.getId()!=null && project.getEmployeeId() !=null && projectAssignment1 !=null){
                projectAssignment1.setProjectId(project.getId());
                projectAssignment1.setEmployeeId(project.getEmployeeId());
            }
        }//两个if都不经过，就是项目负责人没选
        //更新和插入全部放到后面，因为项目参与人数还没有算好(不知道负责人在不在里面)

        //首先项目负责人如果没填，就没必要查询参与人员列里有没有负责人的信息了
        int count = 0;
        if(project.getEmployeeId()!=null) {
            //如果参与人员列里没有选中负责人，则需要另外插入
            LambdaQueryWrapper<Participant> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(Participant::getProjectId, project.getId());
            queryWrapper1.eq(Participant::getEmployeeId, project.getEmployeeId());
            count = participantMapper.selectCount(queryWrapper1);
        }
//           System.out.println("项目负责人信息在participant里面了吗："+count);
           if (count == 0) {// && project.getEmployeeId()!=null
//               System.out.println("项目负责人信息还没有插入"+count);
               //项目负责人信息还没有插入
               Participant participant = new Participant();

               if(project.getEmployeeId()!=null){
                    participant.setProjectId(project.getId());
                    participant.setEmployeeId(project.getEmployeeId());
                    participantService.save(participant);
                }
               //负责人还没插入，插入后数量+1
               //更新项目参与表的参与人数+1
               if(projectAssignment!=null) {
//                   System.out.println("更新人数");
                   projectAssignment.setParticipants(employeeIds.size() + 1);
                   projectAssignmentsMapper.updateById(projectAssignment);
               }
               //插入项目参与表的参与人数+1
//               System.out.println("projectAssignment1是"+projectAssignment1);
               if(projectAssignment1.getProjectId()!=null) {
//                   System.out.println("新增人数");
                   projectAssignment1.setParticipants(employeeIds.size() + 1);
                   projectAssignmentsMapper.insert(projectAssignment1);
               }
           }else{
               //负责人已经插入到Participants表了，就用employeeIds.size作为参与人数
               if(projectAssignment!=null) {
//                   System.out.println("查到了该项目的分配信息,更新"+projectAssignment);
                   projectAssignment.setParticipants(employeeIds.size());
                   projectAssignmentsMapper.updateById(projectAssignment);
               }
               //负责人已经插入到Participants表，直接用employeeIds.size作为参与人数
               //负责人离职后，删除了项目分配表，修改项目时，提交的时候，没有负责人，所以没有项目参与人数，需要手动设置
//               System.out.println("project.getEmployeeId()是："+project.getEmployeeId());
//               System.out.println("projectAssignment是："+projectAssignment);
               //查不到该项目的分配信息，前端也选择了项目负责人,插入项目分配信息
               if(project.getEmployeeId()!=null && projectAssignment == null) {
//                   System.out.println("查不到该项目的分配信息，前端也选择了项目负责人,插入项目分配信息");
                   projectAssignment1.setParticipants(employeeIds.size());
                   projectAssignmentsMapper.insert(projectAssignment1);
               }
           }
//        }
        Client client = clientService.getById(project.getClientId());
        if(client == null && project.getClientId()!=null){
//            projectService.update(new UpdateWrapper<Project>().lambda()
//                            .set(Project::getClientId,null)
//                            .eq(Project::getId,project.getId()));
//            projectService.updateById(project);
            // 将 clientId 设置为 null
//            project.setClientId(null);
            //显示的设置回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new Result(Code.SAVE_ERR,"所选客户信息已被删除，请重新选择");
        }
        projectService.updateById(project);
        return new Result(Code.UPDATE_OK,"项目信息修改成功");
    }

    //新增项目
    @PostMapping("/addProject")
    @Transactional
    public Result save(@RequestBody Project project){
//        System.out.println("新增项目，项目信息是："+project);

        if(project.getPid() == null){
            Random random = new Random();
            // 生成一个 15 位的随机数字
            long pid = 100000000000000L + (long)(random.nextDouble() * 90000000000000L);
            project.setPid(String.valueOf(pid));
        }

//        System.out.println("project.getEndDate()是："+project.getEndDate());
//        // 定义一个 DateTimeFormatter，指定输入的日期时间格式
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        // 使用 formatter 解析字符串
//        LocalDateTime endDate = LocalDateTime.parse(project.getEndDate().toString(), formatter);
//        project.setEndDate(endDate);

        Client client = clientService.getById(project.getClientId());
        if(client == null && project.getClientId()!=null){
            projectService.update(new UpdateWrapper<Project>().lambda()
                    .set(Project::getClientId,null)
                    .eq(Project::getId,project.getId()));
            // 将 clientId 设置为 null
//            project.setClientId(null);
            return new Result(Code.SAVE_ERR,"所选客户信息已被删除，请重新选择");
        }
        projectService.save(project);

        //如果是自己添加项目，默认负责人是自己，前端就会有employeeId传来，顺便要插入项目参与表
        if(project.getEmployeeId() != null){
            Participant participant = new Participant();
            participant.setProjectId(project.getId());
            participant.setEmployeeId(project.getEmployeeId());
            participantService.save(participant);
            ProjectAssignments projectAssignment = new ProjectAssignments();
            projectAssignment.setProjectId(project.getId());
            projectAssignment.setEmployeeId(project.getEmployeeId());
            projectAssignment.setParticipants(1);
            projectAssignmentsMapper.insert(projectAssignment);
        }

        if(client!=null){
            client.setStatus(StatusMessageConstant.ClientOperationSuccess);//把合作状态设为合作中
            clientService.updateById(client);//更新到数据库
        }
//save方法继承自mybatis-plus的父接口IService（看看application.yml文件）,可以直接调用
        return new Result(Code.SAVE_OK,"新增项目成功，已变更客户合作状态");
    }

}
